package com.zheng.oss.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.util.Auth;
import com.zheng.oss.common.constant.OssConstant;
import com.zheng.oss.common.constant.OssResult;
import com.zheng.oss.common.constant.OssResultConstant;
import com.zheng.oss.common.model.QiniuCallback;
import com.zheng.oss.web.service.AliyunOssService;
import com.zheng.oss.web.service.QiniuOssService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by ZhangShuzheng on 2017/5/15.
 */
@Controller
@RequestMapping("/qiniuyun/oss")
public class QiniuyunOssController {

    private static Logger _log = LoggerFactory.getLogger(QiniuyunOssController.class);

    @Autowired
    private QiniuOssService qiniuyunOssService;

    /**
     * 签名生成
     *
     * @param callback 跨域请求
     * @return
     */
    @GetMapping("/policy")
    @ResponseBody
    //@CrossOrigin(origins = "*", methods = RequestMethod.GET) // 该注解不支持JDK1.7
    public Object policy(@RequestParam(required = false) String callback) {
        JSONObject result = qiniuyunOssService.policy();
        if (StringUtils.isBlank(callback)) {
            return result;
        }
        MappingJacksonValue jsonp = new MappingJacksonValue(result);
        jsonp.setJsonpFunction(callback);
        return jsonp;
    }

    /**
     * 上传成功回调方法
     *
     * @param request
     * @return
     */
    @PostMapping("callback")
    @ResponseBody
    public Object callback(HttpServletRequest request) {

        //通过获取请求的HTTP头部Authorization字段获得
        String callbackAuthHeader = request.getHeader("Authorization");
        //通过读取回调POST请求体获得，不要设置为null
        byte[] callbackBody = new byte[1024];
        try {
            //这里是最重要的，接收byte[]
            request.getInputStream().read(callbackBody);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (qiniuyunOssService.isValidCallback(callbackAuthHeader, callbackBody)) {
            //将byte[]转化为字符串
            String callbackBodyStr = new String(callbackBody);

            //将字符串转化为json对象
            JSONObject obj = JSONObject.parseObject(callbackBodyStr);

            JSONObject data = new JSONObject();
            String filename = obj.get("key").toString();
            filename = "http://".concat(OssConstant.OSS_DOMAINOfBUCKET).concat(".").concat("/").concat(filename);
            data.put("key", obj.get("key"));
            data.put("bucket", obj.get("bucket"));
            data.put("filename", filename);
            data.put("hash", obj.get("hash"));
            data.put("bucket", obj.get("bucket"));
            data.put("fsize", obj.get("fsize"));
            return new OssResult(OssResultConstant.SUCCESS, data);
        }else {
            return new OssResult(OssResultConstant.FAILED,null);
        }
    }
}
